package pe.com.trestperu.common.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
 * 
 *
 * @author 3T Peru Solutions Provider SAC
 *
 */
public class SendMail extends JavaMailSenderImpl{
	
	private static final Log log = LogFactory.getLog(SendMail.class);

    private Map<String, Object> attachFile = new HashMap<String, Object>();
    private String from;
    private String[] to;
    private String text;
    private String subject;
    private boolean textHtml = false;

    public void setAttachFile(Map<String, Object> attachFile) {
		this.attachFile = attachFile;
	}

	public void setTo(String[] to) {
		this.to = to;
	}

	public void setTo(String to) {
		this.to = new String[]{to};
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public void setText(String text) {
		this.text = text;
	}

	public void setTextHtml(boolean textHtml) {
		this.textHtml = textHtml;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public void sendMail() throws Exception{
    	MimeMessage message = this.createMimeMessage();

    	message.setFrom(new InternetAddress(from));
    	message.setSubject(subject);
    	MimeMessageHelper helper =  new MimeMessageHelper(message, false);
    	if(MapUtils.isNotEmpty(attachFile)){
    		helper = new MimeMessageHelper(message, true);
        	Iterator<?> it = attachFile.keySet().iterator();
        	while(it.hasNext()){
        		Object key = it.next();
        		Object file = attachFile.get(key);
        		if(ClassUtils.isAssignable(file.getClass(), File.class)){
	        		File attach = (File)file;
	        		log.info("[CoreMail :: attaching File] :: ".concat(attach.getName()));
	        		helper.addAttachment(attach.getName(), attach);
        		}else{
        			if(ClassUtils.isAssignable(file.getClass(), String.class)){
        				File attach = new File((String)file);
        				log.info("[CoreMail :: attaching File] :: ".concat(attach.getName()));
        				helper.addAttachment(attach.getName(), attach);
        			}else{
        				log.warn("[CoreMail :: Caution]Attached not valid");
        			}
        		}
        	}
    	}else{
    		helper = new MimeMessageHelper(message, false);
    	}

    	// true = HTML content
    	helper.setText(text, textHtml);
    	helper.setTo(to);
    	
    	this.send(message);
    	log.info("[CoreMail :: Proccess] Mail sended");
    }
}